package com.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Aspect
@Order(1) //值越小，优先级越高，用于多个切面
public class MyAspect {


    /**
     *前置
     */
    @Before("execution(* com.example.aop.*.*(..))")
    public void before(JoinPoint point) {
        System.out.println("before");
    }

    /**
     * 后置
     */
    @After("execution(* com.example.aop.*.*(..))")
    public void after(JoinPoint point) {
        System.out.println("after");
    }

    /**
     * 返回
     */
    @AfterReturning(value = "execution(* com.example.aop.*.*(..))", returning = "res")
    public void afterReturn(JoinPoint point, Object res) {
        System.out.println("afterReturn" + res);
    }

    /**
     * 异常(2018.8.18测试，环绕走完只有异常不走)
     */
    @AfterThrowing(value = "execution(* com.example.aop.*.*(..))", throwing = "ex")
    public void afterThrow(Exception ex) {
        ex.printStackTrace();
        System.out.println("afterThrow" + ex.getLocalizedMessage());
    }

    /**
     * 环绕
     * 类似动态代理的全过程
     */
    //@Around("execution(* com.example.aop.*.*(..))")
    public Object around(ProceedingJoinPoint point) {
        Object res = null;
        try {
            System.out.println("before");
            res = point.proceed();
            System.out.println("after");
        }
        catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("exception" + throwable.getLocalizedMessage());
        }
        System.out.println("return");
        return res;
    }

}






